package cn.jly.servlet3;

import cn.jly.servlet3.filter.UserFilter;
import cn.jly.servlet3.listener.UserListener;
import cn.jly.servlet3.service.HelloService;
import cn.jly.servlet3.servlet.UserServlet;

import javax.servlet.*;
import javax.servlet.annotation.HandlesTypes;
import java.util.EnumSet;
import java.util.Set;

/**
 * @author lanyangji
 * @description 自定义ServletContainerInitializer
 * @date 2020/11/14 下午 4:44
 */
@HandlesTypes(value = {HelloService.class}) // 传入感兴趣的类型
public class MyServletContainerInitializer implements ServletContainerInitializer {
    /**
     * 使用servletContext注册三大组件
     *
     * @param set            所有感兴趣的类型及其子类型，或者实现类
     * @param servletContext 当前web应用的ServletContext，一个web应用对应一个ServletContext
     * @throws ServletException
     */
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        System.out.println("感兴趣的类型：");
        for (Class<?> clazz : set) {
            System.out.println("clazz = " + clazz);
        }

        // 注册三大组件
        // servlet
        final ServletRegistration.Dynamic userServlet = servletContext.addServlet("userServlet", UserServlet.class);
        userServlet.addMapping("/userServlet");

        // listener
        servletContext.addListener(UserListener.class);

        // filter
        final FilterRegistration.Dynamic userFilter = servletContext.addFilter("userFilter", UserFilter.class);
        userFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
    }
}
